import { modelService } from "@/modules/model/service";
import { ref } from "vue";
import { AddModelItem, PropertyDropdownOption, PropertyRow } from "../../types";

export function useLoadItemsOptions(row: PropertyRow, loadFn?: () => Promise<PropertyDropdownOption[]>, projectId?: string) {
  let loading = false;
  let loaded = false;
  const options = ref<PropertyDropdownOption[]>([]);

  async function loadOptions() {
    console.log("AAAA");
    if (!projectId) {
      projectId = app.activeProject?.id;
    }
    if (!projectId || loaded || loading) return;

    loading = true;
    try {
      options.value = loadFn ? await loadFn() : await modelService.getPropertyItems(projectId, row.modelId, row.key);

      loaded = true;
    } finally {
      loading = false;
    }
  }

  function clear() {
    loading = false;
    loaded = false;
    options.value = [];
  }

  return {
    loadOptions,
    clear,
    options
  };
}
export function useLoadAddItems(row: PropertyRow, loadFn?: () => Promise<AddModelItem[]>) {
  let loading = false;
  let loaded = false;
  const addModelItems = ref<AddModelItem[]>([]);

  async function loadOptions() {
    const projectId = app.activeProject?.id;
    const modelId = row.modelId;
    const modelIds = row.modelIds;
    if (!projectId || (!modelId && !modelIds) || loaded || loading) return;

    loading = true;
    try {
      addModelItems.value = loadFn ? await loadFn() : await modelService.getPropertyAddModelItems(projectId, modelId, modelIds, row.key);
      loaded = true;
    } finally {
      loading = false;
    }
  }
  function clear() {
    loading = false;
    loaded = false;
    addModelItems.value = [];
  }

  return {
    loadOptions,
    clear,
    addModelItems
  };
}
